#include "m0wig.h"
#include "ui_m0wig.h"
#include "globalval.h"

M0Wig::M0Wig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::M0Wig)
{
    ui->setupUi(this);






    udpsocket = new QUdpSocket(this);
    socket1 = new QTcpSocket(this);
    socket2 = new QTcpSocket(this);

    ui->label_2->setPixmap(QPixmap(":/new/prefix1/dk.png"));
    ui->label_2->setScaledContents(true);

    //
    ui->label->setStyleSheet("color: white;"
                             "font-size: 60px;");
    ui->comboBox->setStyleSheet( "background-color: rgb(42, 44, 70);"
                                 "color:white;"
                                 "border-style: outset;"
                                 "border-width: 2px;"
                                 "border-radius: 10px;"
                                 "border-color: beige;"
                                 "font: bold 20px;"
                                 "min-width: 5em;"
                                 //
                                 "}"
                                 "QPushButton:pressed {"
                                 "background-color: rgb(70, 70, 162);"
                                 "border-style: inset");
    ui->pushButton->setStyleSheet( "background-color: rgb(42, 44, 70)  ;"
                                   "color:white;"
                                   "border-style: outset;"
                                   "border-width: 2px;"
                                   "border-radius: 10px;"
                                   "border-color: beige;"
                                   "font: bold 20px;"
                                   "min-width: 6em;"

                                   "}"
                                   "QPushButton:pressed {"
                                   "background-color: rgb(70, 70, 162);"
                                   "border-style: inset");

    ui->pushButton_2->setStyleSheet( "background-color: rgb(42, 44, 70);;"
                                     "color:white;"
                                     "border-style: outset;"
                                     "border-width: 2px;"
                                     "border-radius: 10px;"
                                     "border-color: beige;"
                                     "font: bold 20px;"
                                     "min-width: 6em;"

                                     "}"
                                     "QPushButton:pressed {"
                                     "background-color: rgb(70, 70, 162);"
                                     "border-style: inset");
    ui->pushButton_3->setStyleSheet( "background-color: rgb(42, 44, 70) ;"
                                     "color:white;"
                                     "border-style: outset;"
                                     "border-width: 2px;"
                                     "border-radius: 10px;"
                                     "border-color: beige;"
                                     "font: bold 20px;"
                                     "min-width: 6em;"

                                     "}"
                                     "QPushButton:pressed {"
                                     "background-color: rgb(70, 70, 162);"
                                     "border-style: inset");
    bindPort();
    connect(ui->pushButton,SIGNAL(clicked()),
            this,SLOT(on_btnBroadcast_clicked()));
    connect(udpsocket, SIGNAL(readyRead()),
            this,SLOT(onSocketReadyRead()));

    connect(ui->pushButton_2,SIGNAL(clicked()),
            this,SLOT(tcpClient()));

    connect(socket1, SIGNAL(readyRead()),
            this,SLOT(socketRead()));

    connect(socket2, SIGNAL(readyRead()),
            this,SLOT(socket2Read()));

    connect(socket1,SIGNAL(connected()),
            this,SLOT(socketSend()));

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()),
            this,SLOT(sendHeartbeat()));

    connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),
            this,SLOT(control(int)));
    connect(ui->pushButton_3,SIGNAL(clicked()),
            this,SLOT(xin()));
}
M0Wig::~M0Wig()
{
    if(socket1->isOpen())// 如果数据流在打开状态
        socket1->close();
    if(socket2->isOpen())// 如果数据流在打开状态
        socket2->close();
    if(udpsocket->isOpen())// 如果数据流在打开状态
        udpsocket->close();

    if(timer->isActive())
        timer->stop();

    delete ui;
}

void M0Wig::tcpClient()
{

    // 拿到用户输入的IP地址和端口号
    QHostAddress ip = peerAddr;
    quint16 port = targetPort;
    // 连接到服务器
    socket1->connectToHost(ip,port);

}

void M0Wig::socketSend()
{
    QString text ="{\"type\": 1}";
    QTextStream output(socket1);
    output << text;
}

void M0Wig::socket2Send()
{
    qDebug() << "开始发送文件";
    QFile readFile(":/new/prefix1/pointtable.json");
    // 打开文件流
    readFile.open(QIODevice::ReadOnly);
    QByteArray buffer;
    while(!readFile.atEnd()) // 判断是否位于文件尾部
    {
        // 读取数据
        buffer = readFile.read(1024);
        socket2->write(buffer);
    }
    qDebug() << "文件发送完毕";
    readFile.close();

}

void M0Wig::sendHeartbeat()
{
    QJsonObject json;
    json["type"] = 3;

    QJsonDocument jsonDoc(json);

    QByteArray jsonData = jsonDoc.toJson();

    // 发送JSON数据
    socket1->write(jsonData);

    // 等待数据发送完毕
    if (socket1->waitForBytesWritten()) {
        // qDebug() << "JSON data sent successfully1";
    } else {
        qDebug() << "Failed to send JSON data";
    }

    if (!socket1->waitForReadyRead(3000))
    {
        ui->label_2->setPixmap(QPixmap(":/new/prefix1/dk.png"));
        ui->label_2->setScaledContents(true);
        qDebug() << "Connection is not active or timed out.";
    }else
    {
        ui->label_2->setPixmap(QPixmap(":/new/prefix1/cr.png"));
        ui->label_2->setScaledContents(true);
        qDebug() << "okkk";
    }
}

void M0Wig::control(int i)
{
    if(i == 0)
    {
        ui->pushButton_3->setEnabled(true);
        QJsonObject modChangeObj;
        modChangeObj.insert("type",3);
        QJsonObject dataObj;
        dataObj.insert("type",0);
        dataObj.insert("period",5);
        modChangeObj.insert("data",dataObj);


        QJsonDocument send;
        send.setObject(modChangeObj);

        QByteArray byteArr = send.toJson();
        emit con(byteArr);
    }
    if(i == 1)
    {
        ui->pushButton_3->setEnabled(false);
        QJsonObject modChangeObj;
        modChangeObj.insert("type",3);
        QJsonObject dataObj;
        dataObj.insert("type",1);
        dataObj.insert("period",5);
        modChangeObj.insert("data",dataObj);


        QJsonDocument send;
        send.setObject(modChangeObj);

        QByteArray byteArr = send.toJson();
        emit con(byteArr);
    }
    if(i == 2)
    {
        ui->pushButton_3->setEnabled(false);
        QJsonObject modChangeObj;
        modChangeObj.insert("type",3);
        QJsonObject dataObj;
        dataObj.insert("type",2);
        dataObj.insert("period",2);
        modChangeObj.insert("data",dataObj);


        QJsonDocument send;
        send.setObject(modChangeObj);

        QByteArray byteArr = send.toJson();
        emit con(byteArr);
    }
}

void M0Wig::xin()
{
    QJsonObject modChangeObj;
    modChangeObj.insert("type",1);

    QJsonDocument send;
    send.setObject(modChangeObj);
    QByteArray byteArr = send.toJson();
    emit con(byteArr);
}


//绑定端口
void M0Wig::bindPort()
{
    quint16 port = 6666; // 本机UDP端口
    if (udpsocket->bind(port)) // 绑定端口成功
    {
        qDebug() << "**已成功绑定" ;
        //        qDebug() << "**本机端口：" << QString::number(udpsocket->localPort());
    }
    else
        qDebug() << "**绑定失败";
}

void M0Wig::socketMqtt(QByteArray msg)
{

    qDebug() << "socket1反序列化\n";

    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(msg, &error);

    // 检查解析是否出错
    if (error.error != QJsonParseError::NoError) {
        qDebug() << "Error parsing JSON:" << error.errorString();

    }

    // 将JSON转换为对象
    if (!jsonDoc.isObject()) {
        qWarning() << "JSON is not an object.";
        return;
    }

    // 获取根对象
    QJsonObject jsonObj = jsonDoc.object();

    // 从对象中获取数据
    if (jsonObj.contains("type") && jsonObj["type"].isDouble()) {
        int type = jsonObj["type"].toInt(); // 获取type字段的整数值
        qDebug() << "Type:" << type;
    }

    if (jsonObj.contains("result") && jsonObj["result"].isDouble()) {
        int result = jsonObj["result"].toInt(); // 获取result字段的整数值
        qDebug() << "Result:" << result;
    }

    if (jsonObj.contains("up_config") && jsonObj["up_config"].isString()) {
        QString upConfig = jsonObj["up_config"].toString(); // 获取up_config字段的字符串值
        qDebug() << "Up Config:" << upConfig;
        if( upConfig == "ture")
            Send1Slot();
    }
}

void M0Wig::socketMqtt2(QByteArray msg)
{
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(msg, &error);

    if (error.error != QJsonParseError::NoError) {
        qWarning() << "Failed to parse JSON:" << error.errorString();
        return;
    }

    // 检查JSON的根对象是否是一个对象
    if (!jsonDoc.isObject()) {
        qWarning() << "JSON document is not an object.";
        return;
    }

    // 获取根对象
    QJsonObject jsonObj = jsonDoc.object();

    // 提取type字段
    if (jsonObj.contains("type"))
    {
        int type = jsonObj["type"].toInt();
        qDebug() << "Type:" << type;
    }

    // 提取data字段
    if (jsonObj.contains("data"))
    {
        QJsonObject dataObj = jsonObj["data"].toObject();
        if (dataObj.contains("flag"))
        {
            QString flag = dataObj["flag"].toString();
            qDebug() << "Flag:" << flag;
            if(flag == "start")
            {
                socket2Send();
                return;
            }
        }
    }
}

// 广播消息 按钮
void M0Wig::on_btnBroadcast_clicked()
{
    targetPort = 8877; //目标端口
    QString msg="coffee";
    QByteArray str=msg.toUtf8();
    udpsocket->writeDatagram(str,QHostAddress("192.168.50.255"),targetPort);
}

void M0Wig::onSocketReadyRead()
{
    while(udpsocket->hasPendingDatagrams())  // 判断是否有待读取的数据
    {
        QByteArray datagram;
        datagram.resize(udpsocket->pendingDatagramSize()); // 获取待读取数据报的字节数


        quint16 peerPort;
        udpsocket->readDatagram(datagram.data(),datagram.size(),&peerAddr,&peerPort); // 读取数据报内容

        qDebug() << peerAddr.toString();
        QString str=datagram.data();

        QString peer="[From "+peerAddr.toString()+":"+QString::number(peerPort)+"] ";

        //        ui->textBrowser->setText(peer+str);

        if( str == "yes")
        {
            qDebug() <<"yes";
            ui->textBrowser->setText(peerAddr.toString());
            return;
        }
    }
}



void M0Wig::socketRead()
{

    QByteArray buffer = socket1->readAll();
    qDebug() << buffer;
    QString text(buffer);
    //    ui->textBrowser->setText(text);
    socketMqtt(buffer);

}

void M0Wig::socket2Read()
{
    qDebug() <<"socket2解析";
    QByteArray buffer = socket2->readAll();
    qDebug() << buffer;
    socketMqtt2(buffer);
}

void M0Wig::Send1Slot()
{
    qDebug() <<"没有点表";
    QHostAddress ip = peerAddr;
    // 获得用户要发送的信息
    QString text = "new";
    QByteArray buffer = text.toUtf8();
    // 发送
    socket1->write(buffer);
    timer->start(3000);

    socket2->connectToHost(ip,6666);
    ui->label_2->setPixmap(QPixmap(":/new/prefix1/cr.png"));
    ui->label_2->setScaledContents(true);
    qDebug() << "socket2开启";
    QString text2 = "{\"type\": 2,\"data\": {\"flag\":\"start\",\"file_name\":\"pointta.json\", \"file_len\":1024}}";
    QByteArray buffer2 = text2.toUtf8();
    socket2->write(buffer2);
}

void M0Wig::paintEvent(QPaintEvent *event)
{
    //
    QPainter painter(this);
    QPixmap map(":/new/prefix1/00.png");
    // 绘制图片
    // 参数1、2 横轴及纵轴坐标
    // 参数3、4 绘制的宽高
    // 参数5    绘制的内容
    painter.drawPixmap(0,0,width(),height(),map);
}


